//
//  ViewController.m
//  19-JSON-WYNews
//
//  Created by Snow on 16/8/9.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "ViewController.h"
#import "NewsTitle.h"
#import "MyLayout.h"
#import "MyCollectionViewCell.h"
@interface ViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, GXLabelWidth>
@property (nonatomic, strong) NSMutableArray <NewsTitle *> *arrayOfNews;
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self handleData];
    MyLayout *layout = (MyLayout *)_myCollectionView.collectionViewLayout;
    self.automaticallyAdjustsScrollViewInsets = NO;
    layout.delegate = self;
}

- (void)handleData
{
    _arrayOfNews = [NSMutableArray array];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSDictionary *JSONDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
           
    NSArray *list = JSONDic[@"tList"];
    for (NSDictionary *dic in list) {
    NewsTitle *newTitle = [NewsTitle newsTitleWithDic:dic];
    [_arrayOfNews addObject:newTitle];
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _arrayOfNews.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    NewsTitle *newTitle = [_arrayOfNews objectAtIndex:indexPath.row];
    cell.labelOfTitle.text = newTitle.tname;
    return cell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout height:(CGFloat)height heightForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NewsTitle *newsTitle = [_arrayOfNews objectAtIndex:indexPath.row];
    CGRect newRect = [newsTitle.tname boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 40) options:1 attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    CGFloat width = ceilf(CGRectGetWidth(newRect));//取整函数
    return  width;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end
